<template>
  <div class="achievements-page">
    <div class="page-header">
      <div class="header-content">
        <div class="header-top">
          <h1>我的成就</h1>
          <el-button type="primary" @click="goToHome" class="back-button">
            <el-icon><Back /></el-icon>
            <span>返回首页</span>
          </el-button>
        </div>
        <p class="header-subtitle">收集成就，展示你的学习历程</p>
      </div>
      <div class="achievement-stats">
        <div class="stat-item">
          <div class="stat-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ totalAchievements }}</div>
            <div class="stat-label">已获得成就</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ totalCheckinAchievements }}</div>
            <div class="stat-label">签到成就总数</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon">
            <el-icon><Star /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ totalPoints }}</div>
            <div class="stat-label">累计积分</div>
          </div>
        </div>
      </div>
    </div>
    
    <el-tabs v-model="activeTab" class="achievement-tabs" type="border-card">
      <el-tab-pane label="已获成就" name="checkin">
        <div class="achievement-section">
          <div class="section-header">
            <h2>已获成就</h2>
            <div class="section-actions">
              <el-tooltip content="按获得时间排序" placement="top">
                <el-button type="primary" text>
                  <el-icon><Sort /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="achievement-grid">
            <achievement-badge
              v-for="achievement in checkinAchievementsList"
              :key="achievement.id"
              :id="achievement.id"
              :name="achievement.name"
              :description="achievement.description"
              :icon-url="achievement.iconUrl"
              :earned="achievement.earned"
              :earned-date="achievement.earnedDate"
              :condition-type="achievement.conditionType"
              :condition-value="achievement.conditionValue"
              :points-reward="achievement.pointsReward"
            />
          </div>
          <div v-if="checkinAchievementsList.length === 0" class="empty-state">
            <el-icon><InfoFilled /></el-icon>
            <p>暂无已获得的成就，继续努力吧！</p>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="全部成就" name="all">
        <div class="achievement-section">
          <div class="section-header">
            <h2>全部成就</h2>
            <div class="section-actions">
              <el-tooltip content="按难度排序" placement="top">
                <el-button type="primary" text>
                  <el-icon><Sort /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="achievement-grid">
            <achievement-badge
              v-for="achievement in allAchievements"
              :key="achievement.id"
              :id="achievement.id"
              :name="achievement.name"
              :description="achievement.description"
              :icon-url="achievement.iconUrl"
              :earned="achievement.earned"
              :earned-date="achievement.earnedDate"
              :condition-type="achievement.conditionType"
              :condition-value="achievement.conditionValue"
              :points-reward="achievement.pointsReward"
            />
          </div>
          <div v-if="allAchievements.length === 0" class="empty-state">
            <el-icon><Loading /></el-icon>
            <p>正在加载成就数据...</p>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import AchievementBadge from '@/components/AchievementBadge.vue';
import { ElMessage } from 'element-plus';
import { getAchievements, getUserAchievements } from '@/api/achievement';
import { getUserInfo } from '@/api/auth';
import { Trophy, Calendar, Sort, InfoFilled, Loading, Back, Star } from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();
const activeTab = ref('checkin');

// 返回首页方法
const goToHome = () => {
  router.push('/');
};

// 成就数据
const allAchievements = ref([]);
const totalAchievements = ref(0);
const checkinAchievements = ref(0);
const totalPoints = ref(0);

// 计算签到成就列表 - 只显示已获取的成就
const checkinAchievementsList = computed(() => {
  return allAchievements.value.filter(achievement => achievement.category === '签到' && achievement.earned === true);
});

// 计算签到成就总数
const totalCheckinAchievements = computed(() => {
  return allAchievements.value.filter(achievement => achievement.category === '签到').length;
});

// 计算累计积分
const calculateTotalPoints = () => {
  return allAchievements.value
    .filter(achievement => achievement.earned)
    .reduce((total, achievement) => total + achievement.pointsReward, 0);
};

// 获取成就数据
const fetchAchievements = async () => {
  try {
    // 检查用户是否登录
    console.log('检查登录状态:', userStore.isLoggedIn, '用户信息:', userStore.userInfo);
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return;
    }
    
    // 获取用户成就
    console.log('开始获取用户成就');
    const userAchievementsRes = await getUserAchievements();
    console.log('用户成就响应:', userAchievementsRes);
    if (userAchievementsRes.code === 200 && userAchievementsRes.data) {
      // 设置统计数据
      totalAchievements.value = userAchievementsRes.data.totalCount || 0;
      checkinAchievements.value = userAchievementsRes.data.checkinCount || 0;
      
      // 更新累计积分
      totalPoints.value = userAchievementsRes.data.totalPoints || calculateTotalPoints();
      
      // 获取所有成就定义
      console.log('开始获取所有成就定义');
      const achievementsRes = await getAchievements();
      console.log('所有成就响应:', achievementsRes);
      if (achievementsRes.code === 200 && achievementsRes.data) {
        // 合并成就定义和用户成就状态
        const userAchievementMap = {};
        userAchievementsRes.data.achievements.forEach(ua => {
          userAchievementMap[ua.achievementId] = ua;
        });
        
        // 修复：使用 achievementsRes.data.list 而不是 achievementsRes.data
        allAchievements.value = achievementsRes.data.list.map(achievement => {
          const userAchievement = userAchievementMap[achievement.achievementId];
          return {
            id: achievement.achievementId,
            name: achievement.name,
            description: achievement.description,
            iconUrl: achievement.iconUrl,
            category: achievement.category,
            conditionType: achievement.conditionType,
            conditionValue: achievement.conditionValue,
            pointsReward: achievement.pointsReward,
            earned: !!userAchievement,
            earnedDate: userAchievement ? userAchievement.earnedDate : null
          };
        });
      }
    }
  } catch (error) {
    console.error('获取成就数据失败:', error);
    if (error.message === 'AUTH_RETRY') {
      ElMessage.warning('登录状态已过期，请重新登录');
      router.push('/login');
    } else {
      ElMessage.error(`获取成就数据失败: ${error.message || '未知错误'}`);
    }
  }
};

onMounted(async () => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      console.log('从localStorage恢复token');
      userStore.setToken(storedToken);
      // 尝试获取用户信息
      try {
        const userInfoRes = await getUserInfo();
        if (userInfoRes.code === 200 && userInfoRes.data) {
          userStore.setUserInfo(userInfoRes.data);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
  }
  
  // 获取成就数据
  fetchAchievements();
});
</script>

<style scoped>
.achievements-page {
  padding: 32px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f9f9f9;
  min-height: calc(100vh - 64px);
  /* 苹果风格：增加留白和柔和背景 */
  background: linear-gradient(180deg, #f5f7fa 0%, #f0f2f5 100%);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 28px;
  border-radius: 16px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1); /* 苹果风格阴影 */
  position: relative;
  overflow: hidden;
  /* 苹果风格：增加微妙的光泽效果 */
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  /* 苹果风格：添加动画效果 */
  animation: scaleIn 0.6s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.page-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  transform: rotate(30deg);
  z-index: 1;
}

.header-content {
  position: relative;
  z-index: 2;
}

.header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.back-button {
  background-color: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px; /* 苹果风格大圆角 */
  padding: 8px 16px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 苹果风格阴影 */
  /* 苹果风格：增加光泽效果 */
  backdrop-filter: blur(5px);
}

.back-button:hover {
  background-color: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2); /* 苹果风格增强阴影 */
  /* 苹果风格：增加缩放效果 */
  transform: translateY(-2px) scale(1.05);
}

.back-button .el-icon {
  font-size: 16px;
}

.back-button span {
  font-weight: 500;
}

.header-content h1 {
  font-size: 30px;
  color: white;
  margin: 0;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  padding-left: 16px;
}

.header-content h1::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 28px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 3px;
}

.header-subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin: 8px 0 0 16px;
  font-weight: 400;
  max-width: 70%;
  line-height: 1.4;
}

.achievement-stats {
  display: flex;
  gap: 24px;
  position: relative;
  z-index: 2;
}

.stat-item {
  display: flex;
  background: rgba(255, 255, 255, 0.15);
  padding: 16px 20px;
  border-radius: 12px; /* 苹果风格圆角 */
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  align-items: center;
  gap: 16px;
  min-width: 160px;
  /* 苹果风格：增加微妙的光泽和阴影 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  /* 苹果风格：添加动画效果 */
  animation: bounce 1s ease infinite;
  animation-iteration-count: 1;
}

.stat-item:hover {
  transform: translateY(-5px);
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15); /* 苹果风格增强阴影 */
  /* 苹果风格：增加缩放效果 */
  transform: translateY(-5px) scale(1.02);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%; /* 苹果风格圆形设计 */
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 苹果风格阴影 */
  transition: all 0.3s ease;
  /* 苹果风格：增加光泽效果 */
  backdrop-filter: blur(2px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.stat-item:hover .stat-icon {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
  /* 苹果风格：增加光泽效果 */
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: white;
  margin-bottom: 6px;
  line-height: 1;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.achievement-tabs {
  background-color: white;
  border-radius: 12px; /* 苹果风格圆角 */
  padding: 24px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1); /* 苹果风格阴影 */
  /* 苹果风格：增加边框和微妙的光泽 */
  border: 1px solid rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(5px);
  /* 苹果风格：添加动画效果 */
  animation: fadeIn 0.7s ease-out;
}

.achievement-section {
  margin-bottom: 40px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05); /* 苹果风格细边框 */
  /* 苹果风格：增加留白 */
  padding: 16px 20px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
  /* 苹果风格：添加动画效果 */
  animation: fadeIn 0.4s ease-out;
}

.section-header h2 {
  font-size: 22px;
  color: #303133;
  margin: 0;
  font-weight: 600;
  position: relative;
}

.section-header h2::after {
  content: '';
  position: absolute;
  bottom: -14px;
  left: 0;
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #1890ff, #69c0ff);
  border-radius: 2px;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.achievement-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 24px;
  padding: 10px;
  /* 苹果风格：增加柔和的背景和内边距 */
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(0, 0, 0, 0.03);
  /* 苹果风格：添加动画效果 */
  animation: fadeIn 0.5s ease-out;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
  background-color: #f9f9f9;
  border-radius: 12px; /* 苹果风格圆角 */
  margin: 20px 0;
  border: 1px dashed rgba(0, 0, 0, 0.1); /* 苹果风格细边框 */
  transition: all 0.3s ease;
  /* 苹果风格：增加柔和阴影和背景 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(5px);
  background: rgba(255, 255, 255, 0.8);
  /* 苹果风格：添加动画效果 */
  animation: fadeIn 0.8s ease-out;
}

.empty-state:hover {
  background-color: #f0f0f0;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1); /* 苹果风格增强阴影 */
  /* 苹果风格：增加微妙的变换效果 */
  transform: scale(1.01);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.empty-state .el-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #c0c4cc;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 苹果风格：增加流畅的弹跳动画 */
@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    transform: translate3d(0, 0, 0);
  }
  40%, 43% {
    transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -8px, 0);
  }
  70% {
    transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -4px, 0);
  }
  90% {
    transform: translate3d(0, -2px, 0);
  }
}

/* 苹果风格：增加淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 苹果风格：增加缩放动画 */
@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 苹果风格：增加流畅的弹跳动画 */
@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
    transform: translate3d(0, 0, 0);
  }
  40%, 43% {
    transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -8px, 0);
  }
  70% {
    transition-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
    transform: translate3d(0, -4px, 0);
  }
  90% {
    transform: translate3d(0, -2px, 0);
  }
}

.empty-state p {
  font-size: 18px;
  margin: 0;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .achievements-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 16px;
    /* 苹果风格：保持一致的圆角 */
    border-radius: 12px;
    /* 苹果风格：保持动画效果 */
    animation: fadeIn 0.6s ease-out;
  }
  
  .header-top {
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
  }
  
  .back-button {
    padding: 6px 12px;
    font-size: 14px;
    /* 苹果风格：保持圆角 */
    border-radius: 16px;
  }
  
  .header-content h1 {
    font-size: 24px;
    padding-left: 14px;
  }
  
  .header-content h1::before {
    height: 22px;
    width: 5px;
  }
  
  .header-subtitle {
    margin-left: 14px;
    font-size: 14px;
    max-width: 100%;
  }
  
  .achievement-stats {
    width: 100%;
    flex-direction: column;
    gap: 12px;
  }
  
  .stat-item {
    width: 100%;
    padding: 12px 16px;
    /* 苹果风格：保持圆角和阴影 */
    border-radius: 10px;
    /* 苹果风格：保持动画效果 */
    animation: bounce 1s ease infinite;
    animation-iteration-count: 1;
  }
  
  .achievement-grid {
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    gap: 16px;
    padding: 5px;
    /* 苹果风格：保持背景和圆角 */
    border-radius: 10px;
    /* 苹果风格：保持动画效果 */
    animation: fadeIn 0.5s ease-out;
  }
  
  .empty-state {
    padding: 40px 0;
    /* 苹果风格：保持圆角 */
    border-radius: 10px;
    /* 苹果风格：保持动画效果 */
    animation: fadeIn 0.8s ease-out;
  }
  
  .empty-state .el-icon {
    font-size: 48px;
  }
  
  .empty-state p {
    font-size: 16px;
  }
  
  .section-header {
    padding: 12px 16px;
    /* 苹果风格：保持圆角 */
    border-radius: 6px;
    /* 苹果风格：保持动画效果 */
    animation: fadeIn 0.4s ease-out;
  }
}
</style>